package com.team.sns.web.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

public class UserLoginFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		
		String userId = (String) session.getAttribute("user");
		if (StringUtils.isNotBlank(userId)) {
			chain.doFilter(request, response);
		} else {
			if (!req.isRequestedSessionIdValid()) {
				res.setHeader("sessionstatus","timeout");
			} else if (req.getHeader("x-requested-with") != null && "XMLHttpRequest".equalsIgnoreCase(req.getHeader("x-requested-with"))) {//ajax timeout heandler
				res.setHeader("sessionstatus","timeout");
			} else {//http timeout heander
				//res.setHeader("sessionstatus","timeout");
				res.sendRedirect("");
			}
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

}
